#!/usr/bin/env bash
# yt-x extension: Local Mix Creator

CLI_LOCAL_PREVIEWS_MIX_CREATOR="$CLI_CACHE_DIR/local_previews_mix_creator"
[ -d "$CLI_LOCAL_PREVIEWS_MIX_CREATOR" ] || mkdir -p "$CLI_LOCAL_PREVIEWS_MIX_CREATOR"
CLI_MIXES_DIR="$CLI_CONFIG_DIR/mixes"; [ -d "$CLI_MIXES_DIR" ] || mkdir -p "$CLI_MIXES_DIR"
[ -d "$CLI_MIXES_DIR/audio" ] || mkdir -p "$CLI_MIXES_DIR/audio"; [ -d "$CLI_MIXES_DIR/video" ] || mkdir -p "$CLI_MIXES_DIR/video"

_ytx_mix_fzf_play_highlighted() {
    local CMD_TO_RUN="$1" FZF_LINE="$2" TEMP_PATHS_FILE="$3" EXTRA_OPTS="$4"
    local RAW_IDX_FIELD ITEM_IDX NUM_IDX TARGET_PATH
    RAW_IDX_FIELD=$(echo "$FZF_LINE" | awk "{print \$1}")
    ITEM_IDX=$(echo "$RAW_IDX_FIELD" | grep -oE "[0-9]+")
    if [[ "$ITEM_IDX" =~ ^[0-9]+$ ]]; then
      NUM_IDX=$((10#$ITEM_IDX));
      if [ "$NUM_IDX" -ne 0 ]; then
        TARGET_PATH=$(sed -n "${NUM_IDX}p" "$TEMP_PATHS_FILE");
        if [ -n "$TARGET_PATH" ] && [ -f "$TARGET_PATH" ]; then
          if [ "$CMD_TO_RUN" = "mpv" ]; then nohup mpv $EXTRA_OPTS "$TARGET_PATH" >/dev/null 2>&1 & disown; fi;
        fi;
      fi;
    fi
}

_ytx_mix_fzf_play_selected_batch() {
    local TEMP_PATHS_FILE="$1" MPV_OPTS="$2"; shift 2
    local selected_fzf_lines=("$@") actual_files_to_play=()
    local RAW_IDX_FIELD ITEM_IDX NUM_IDX TARGET_PATH

    # echo "Batch Play: TMP='$TEMP_PATHS_FILE', OPTS='$MPV_OPTS', Lines=${#selected_fzf_lines[@]}" >> /tmp/fzf_batch_debug.log
    # printf "%s\n" "${selected_fzf_lines[@]}" >> /tmp/fzf_batch_debug.log

    if [ "${#selected_fzf_lines[@]}" -eq 0 ]; then return; fi

    for fzf_line in "${selected_fzf_lines[@]}"; do
        RAW_IDX_FIELD=$(echo "$fzf_line" | awk "{print \$1}")
        ITEM_IDX=$(echo "$RAW_IDX_FIELD" | grep -oE "[0-9]+")
        if [[ "$ITEM_IDX" =~ ^[0-9]+$ ]]; then
            NUM_IDX=$((10#$ITEM_IDX));
            if [ "$NUM_IDX" -ne 0 ]; then
                TARGET_PATH=$(sed -n "${NUM_IDX}p" "$TEMP_PATHS_FILE");
                if [ -n "$TARGET_PATH" ] && [ -f "$TARGET_PATH" ]; then actual_files_to_play+=("$TARGET_PATH"); fi;
            fi;
        fi;
    done

    if [ "${#actual_files_to_play[@]}" -gt 0 ]; then
        # echo "Batch Playing: ${actual_files_to_play[@]}" >> /tmp/fzf_batch_debug.log
        nohup mpv $MPV_OPTS "${actual_files_to_play[@]}" >/dev/null 2>&1 & disown
    fi
}

main() {
  SHELL="bash"; export SHELL FZF_PREVIEW_COLUMNS FZF_PREVIEW_LINES
  export -f _ytx_mix_fzf_play_highlighted _ytx_mix_fzf_play_selected_batch # Export BOTH helpers

  if ! command -v fd >/dev/null 2>&1; then send_notification "Error: 'fd' missing."; return 1; fi
  if ! command -v ffmpegthumbnailer >/dev/null 2>&1; then send_notification "Warning: 'ffmpegthumbnailer' missing."; fi

  local media_type search_path mpv_ctrl_m_opts mpv_ctrl_o_opts # mpv_ctrl_o_opts now for the batch play
  local fd_extensions_args=() temp_paths_file
  temp_paths_file=$(mktemp "${TMPDIR:-/tmp}/ytx_mix_paths.XXXXXX"); #trap 'rm -f "$temp_paths_file" &>/dev/null' EXIT TERM INT

  media_type_selection=$(printf "audio\nvideo\nExit" | launcher "Create mix for which media type?")
  case "$media_type_selection" in
    audio) media_type="audio"; search_path="$DOWNLOAD_DIRECTORY/audio"; mpv_ctrl_m_opts="--no-video"; mpv_ctrl_o_opts="--no-video"; fd_extensions_args=(--extension mp3 --extension flac --extension aac --extension ogg --extension opus --extension wav --extension m4a) ;;
    video) media_type="video"; search_path="$DOWNLOAD_DIRECTORY/videos"; mpv_ctrl_m_opts=""; mpv_ctrl_o_opts=""; fd_extensions_args=(--extension mp4 --extension mkv --extension webm --extension avi --extension mov --extension flv) ;;
    Exit|"") send_notification "Mix creation cancelled."; return 0 ;;
    *) send_notification "Invalid media type selected."; return 1 ;;
  esac
  if ! [ -d "$search_path" ]; then send_notification "Search directory not found: $search_path"; return 1; fi

  local fzf_input_data=() index=0
  while IFS= read -r -d $'\0' full_path; do
    if [ -n "$full_path" ]; then ((index++)); echo "$full_path" >> "$temp_paths_file"; base_name=$(basename "$full_path"); printf -v fzf_line "[%03d] %s" "$index" "$base_name"; fzf_input_data+=("$fzf_line"); fi
  done < <(fd --print0 --type f "${fd_extensions_args[@]}" . "$search_path")
  if [ ${#fzf_input_data[@]} -eq 0 ]; then send_notification "No $media_type files found in $search_path."; return 0; fi

  local preview_script # This is working
  preview_script='selected_line="{}"
    raw_index_field=$(echo "$selected_line" | awk "{print \$1}")
    item_index=$(echo "$raw_index_field" | grep -oE "[0-9]+")
    if ! [[ "$item_index" =~ ^[0-9]+$ ]]; then echo "Preview Err: Idx \"$item_index\" invalid."; exit 0; fi
    item_index_for_sed=$((10#$item_index)); if [ "$item_index_for_sed" -eq 0 ]; then echo "Preview Err: Idx 0."; exit 0; fi
    file_path=$(sed -n "${item_index_for_sed}p" "'"$temp_paths_file"'")
    if [ -z "$file_path" ]; then echo "Preview Err: No path for idx $item_index_for_sed."; exit 0;
    elif ! [ -f "$file_path" ]; then echo "Preview Err: Not file: $file_path"; exit 0; fi
    base_name=$(basename "$file_path"); thumb_cache_dir="'"$CLI_LOCAL_PREVIEWS_MIX_CREATOR"'"
    preview_image_hash=$(echo -n "$file_path" | generate_sha256)
    preview_image_file="$thumb_cache_dir/${preview_image_hash}.jpg"
    if ! [ -s "$preview_image_file" ]; then
      if command -v ffmpegthumbnailer >/dev/null 2>&1; then
        ffmpegthumbnailer -i "$file_path" -o "$preview_image_file" -s 0 -q 7 &>/dev/null
        if [ -s "$preview_image_file" ]; then fzf_preview "$preview_image_file"; else echo "Preview N/A (thumb fail): $base_name"; fi
      else echo "No ffmpegthumbnailer. File: $base_name"; fi
    else fzf_preview "$preview_image_file"; fi'

  ctrl_m_command_str="_ytx_mix_fzf_play_highlighted mpv {} '$temp_paths_file' '$mpv_ctrl_m_opts'"
  # For Ctrl-O: play all currently selected items ({+})
  # The _ytx_mix_fzf_play_selected_batch function takes $1=temp_file, $2=mpv_opts, and then $@ are the fzf lines
  # fzf expands {+} into separate arguments.
  ctrl_o_command_str="_ytx_mix_fzf_play_selected_batch '$temp_paths_file' '$mpv_ctrl_o_opts' {+}"


  selected_lines_str=$(printf "%s\n" "${fzf_input_data[@]}" | \
    fzf --multi --height=100% --layout=reverse --info=inline --border=rounded \
        --prompt="Select files for '$media_type' mix (TAB to select): " \
        --header="ENTER to confirm. CTRL-M to play highlighted. CTRL-O to play ALL TAB-SELECTED." \
        --preview-window="left,35%,border-rounded" \
        --preview="$preview_script" \
        --bind "enter:accept" \
        --bind "ctrl-j:execute-silent($ctrl_m_command_str)" \
        --bind "ctrl-o:execute($ctrl_o_command_str)" \
        --ansi)
  # Using reload() for ctrl-o might keep fzf interactive, or use execute-silent if reload is not desired.
  # reload() expects the command to output a new list for fzf. If we just want to run a command
  # in the background on selected items, execute-silent is better.


  local fzf_exit_status=$?

  if [ -z "$selected_lines_str" ] && [ "$fzf_exit_status" -ne 0 ]; then send_notification "Mix creation aborted by user."; return 0; fi
  if [ -z "$selected_lines_str" ] && [ "$fzf_exit_status" -eq 0 ]; then send_notification "No files selected. Mix creation cancelled."; return 0; fi

  local selected_files_arr=(); while IFS= read -r line; do # ... (same M3U8 creation logic)
    raw_index_field=$(echo "$line" | awk '{print $1}'); item_index=$(echo "$raw_index_field" | grep -oE "[0-9]+");
    if [[ "$item_index" =~ ^[0-9]+$ ]]; then item_index_numeric=$((10#$item_index));
      if [ "$item_index_numeric" -gt 0 ]; then full_path=$(sed -n "${item_index_numeric}p" "$temp_paths_file");
        if [ -n "$full_path" ] && [ -f "$full_path" ]; then selected_files_arr+=("$full_path");
        else send_notification "Warning: Could not get path for index $item_index_numeric from: $line"; fi
      else send_notification "Warning: Index 0 parsed from: $line"; fi
    else send_notification "Warning: Invalid index parsed from selection: $line"; fi
  done <<< "$selected_lines_str"
  if [ ${#selected_files_arr[@]} -eq 0 ]; then send_notification "No valid files processed. Mix creation cancelled."; return 0; fi

  local mix_name; mix_name=$(prompt "Enter a name for your '$media_type' mix");
  if [ -z "$mix_name" ]; then send_notification "No mix name provided. Mix creation cancelled."; return 0; fi
  local sane_mix_filename; sane_mix_filename=$(echo "$mix_name" | sed 's@[^a-zA-Z0-9._-]@_@g'); [ -z "$sane_mix_filename" ] && sane_mix_filename="unnamed_mix_$(date +%s)"
  local m3u8_file_path="$CLI_MIXES_DIR/$media_type/$sane_mix_filename.m3u8"
  if [ -f "$m3u8_file_path" ]; then if ! confirm "Mix '$mix_name' already exists. Overwrite?"; then send_notification "Mix creation aborted."; return 0; fi; fi

  { echo "#EXTM3U"; for file_path_in_mix in "${selected_files_arr[@]}"; do
      if [ -f "$file_path_in_mix" ]; then local filename_with_ext_mix title_mix; filename_with_ext_mix=$(basename "$file_path_in_mix"); title_mix="${filename_with_ext_mix%.*}";
        echo "#EXTINF:-1,$title_mix"; echo "$file_path_in_mix"; echo ""; fi
    done; } > "$m3u8_file_path"
  if [ $? -eq 0 ] && [ -s "$m3u8_file_path" ]; then send_notification "Mix '$mix_name' created successfully at $m3u8_file_path"; else send_notification "Failed to create mix '$mix_name'."; return 1; fi
  return 0
}

# Mock self-test section
# ...
